const CACHE_NAME = 'vr-iot-pwa-v1';
const urlsToCache = [
    '.',
    'index.html',
    'css/style.css',
    'js/main.js',
    'js/frame-sdk.js',
    'js/i18n.js',
    'manifest.json',
    'icons/icon-72.png',
    'icons/icon-96.png',
    'icons/icon-128.png',
    'icons/icon-144.png',
    'icons/icon-152.png',
    'icons/icon-192.png',
    'icons/icon-384.png',
    'icons/icon-512.png',
    // Plugin pages
    '../plugin/home/index.html',
    '../plugin/control/index.html',
    '../plugin/ai/index.html',
    '../plugin/discovery/index.html',
    '../plugin/mine/index.html'
];

// 安装Service Worker并缓存资源
self.addEventListener('install', (event) => {
    event.waitUntil(
        caches.open(CACHE_NAME)
            .then((cache) => {
                console.log('打开缓存');
                return cache.addAll(urlsToCache);
            })
            .then(() => self.skipWaiting())
    );
});

// 激活Service Worker并清理旧缓存
self.addEventListener('activate', (event) => {
    const cacheWhitelist = [CACHE_NAME];
    event.waitUntil(
        caches.keys().then((cacheNames) => {
            return Promise.all(
                cacheNames.map((cacheName) => {
                    if (cacheWhitelist.indexOf(cacheName) === -1) {
                        return caches.delete(cacheName);
                    }
                })
            );
        }).then(() => self.clients.claim())
    );
});

// 使用Cache First策略，优先从缓存获取资源，同时后台更新缓存
self.addEventListener('fetch', (event) => {
    // 不对chrome-extension://和其他非本域请求进行缓存
    if (!event.request.url.startsWith(self.location.origin) || 
        event.request.url.includes('chrome-extension://')) {
        return fetch(event.request).catch(() => {
            // 对于跨域请求失败，可以返回一个默认的响应
            if (event.request.headers.get('accept')?.includes('image/')) {
                return caches.match('icons/icon-192.png');
            }
            return new Response('Network unavailable', {
                status: 408,
                headers: { 'Content-Type': 'text/plain' }
            });
        });
    }

    // 针对HTML页面使用Stale-While-Revalidate策略
    if (event.request.headers.get('accept')?.includes('text/html')) {
        event.respondWith(
            caches.match(event.request)
                .then((cachedResponse) => {
                    // 不管缓存是否存在，都去网络获取最新版本并更新缓存
                    const fetchPromise = fetch(event.request)
                        .then((networkResponse) => {
                            if (!networkResponse || networkResponse.status !== 200 || networkResponse.type !== 'basic') {
                                return networkResponse;
                            }
                            
                            const responseToCache = networkResponse.clone();
                            caches.open(CACHE_NAME).then((cache) => {
                                cache.put(event.request, responseToCache);
                            });
                            return networkResponse;
                        })
                        .catch(() => {
                            // 如果网络请求失败且没有缓存，则返回主页面
                            if (!cachedResponse) {
                                return caches.match('index.html');
                            }
                            return cachedResponse;
                        });
                    
                    // 如果有缓存，先返回缓存，网络请求在后台更新
                    return cachedResponse || fetchPromise;
                })
        );
    } else {
        // 针对静态资源使用Cache First策略
        event.respondWith(
            caches.match(event.request)
                .then((cachedResponse) => {
                    if (cachedResponse) {
                        // 有缓存时返回缓存，同时在后台更新缓存
                        fetch(event.request)
                            .then((networkResponse) => {
                                if (!networkResponse || networkResponse.status !== 200 || networkResponse.type !== 'basic') {
                                    return;
                                }
                                const responseToCache = networkResponse.clone();
                                caches.open(CACHE_NAME).then((cache) => {
                                    cache.put(event.request, responseToCache);
                                });
                            })
                            .catch(() => {}); // 忽略网络错误，继续使用缓存
                        return cachedResponse;
                    }

                    // 没有缓存时，尝试从网络获取
                    return fetch(event.request)
                        .then((networkResponse) => {
                            // 检查响应是否有效
                            if (!networkResponse || networkResponse.status !== 200 || networkResponse.type !== 'basic') {
                                return networkResponse;
                            }

                            // 缓存新获取的资源
                            const responseToCache = networkResponse.clone();
                            caches.open(CACHE_NAME)
                                .then((cache) => {
                                    cache.put(event.request, responseToCache);
                                });

                            return networkResponse;
                        })
                        .catch(() => {
                            // 静态资源回退策略
                            if (event.request.url.endsWith('.js')) {
                                return new Response('// Offline mode: Script unavailable', { headers: { 'Content-Type': 'application/javascript' } });
                            } else if (event.request.url.endsWith('.css')) {
                                return new Response('/* Offline mode: Styles unavailable */', { headers: { 'Content-Type': 'text/css' } });
                            } else if (event.request.url.includes('image/')) {
                                return caches.match('icons/icon-192.png');
                            }
                        });
                })
        );
    }
});

// 添加后台同步支持
self.addEventListener('sync', (event) => {
    if (event.tag === 'sync-user-config') {
        event.waitUntil(syncUserConfig());
    }
});

// 同步用户配置的示例函数
async function syncUserConfig() {
    try {
        // 这里可以实现与服务器同步配置的逻辑
        const clients = await self.clients.matchAll();
        clients.forEach(client => {
            client.postMessage({ type: 'SYNC_COMPLETE' });
        });
    } catch (error) {
        console.error('Sync failed:', error);
    }
}

// 添加推送通知支持（可选）
self.addEventListener('push', (event) => {
    if (!event.data) return;
    
    try {
        const data = event.data.json();
        const options = {
            body: data.body || '您有新的通知',
            icon: 'icons/icon-192.png',
            badge: 'icons/icon-96.png',
            vibrate: [100, 50, 100],
            data: { url: data.url || '/' }
        };
        
        event.waitUntil(
            self.registration.showNotification(data.title || 'VR-IoT', options)
        );
    } catch (error) {
        console.error('Push notification error:', error);
    }
});

self.addEventListener('notificationclick', (event) => {
    event.notification.close();
    
    event.waitUntil(
        clients.matchAll({ type: 'window' }).then((windowClients) => {
            // 如果已有打开的窗口，则聚焦
            for (const client of windowClients) {
                if (client.url === event.notification.data.url && 'focus' in client) {
                    return client.focus();
                }
            }
            // 否则打开新窗口
            if (clients.openWindow) {
                return clients.openWindow(event.notification.data.url);
            }
        })
    );
});

// 处理推送通知
self.addEventListener('push', (event) => {
    if (!event.data) return;
    
    const data = event.data.json();
    const options = {
        body: data.body,
        icon: 'icons/icon-192.png',
        badge: 'icons/icon-72.png',
        data: {
            url: data.url || '.'
        }
    };
    
    event.waitUntil(
        self.registration.showNotification(data.title, options)
    );
});

// 处理通知点击
self.addEventListener('notificationclick', (event) => {
    event.notification.close();
    
    event.waitUntil(
        clients.matchAll({ type: 'window' }).then((clientList) => {
            // 检查是否已经有打开的窗口
            for (const client of clientList) {
                if (client.url === event.notification.data.url && 'focus' in client) {
                    return client.focus();
                }
            }
            // 如果没有打开的窗口，则打开一个新窗口
            if (clients.openWindow) {
                return clients.openWindow(event.notification.data.url);
            }
        })
    );
});